﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
namespace HuaweiCloud.Dotnet.Samples.Common.Repository
{
    /// <summary>
    /// 用于MongoDb 操作的抽象类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class DocRepositoryBase<T> : IDocRepository<T> where T : BaseComponent
    {
        protected readonly IMongoDbContext _context;
        public DocRepositoryBase(IMongoDbContext context)
        {
            _context = context;
        }
        private IMongoCollection<TComponent> GetCollection<TComponent>(string? collection = null) where TComponent : class
        {
            return _context.Database.GetCollection<TComponent>(collection ?? typeof(TComponent).Name);
        }
        public async Task AddAsync(T entity, CancellationToken cancellationToken = default)
        {
            await GetCollection<T>().InsertOneAsync(entity, null, cancellationToken);
        }
        public async Task DeleteAsync(T entity, CancellationToken cancellationToken = default)
        {
            await GetCollection<T>().DeleteOneAsync(i => i.Id == entity.Id, null, cancellationToken);
        }
        public async Task<T?> GetByIdAsync<TId>(TId id, CancellationToken cancellationToken = default) where TId : notnull
        {
            var item = await GetCollection<T>().FindAsync(i => i.Id == Convert.ToString(id));
            return await item.FirstOrDefaultAsync();
        }
        public async Task<List<T>> ListAsync(Expression<Func<T, bool>>? filter = null,CancellationToken cancellationToken = default)
        {
            filter ??= (T config) => true;
            var items = await GetCollection<T>().FindAsync(filter);
            return items.ToList();
        }
        public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
        {
            await GetCollection<T>().ReplaceOneAsync(i => i.Id == entity.Id, entity);
        }
    }
}
